package com.ncs.cns.activity.fragment;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.ncs.cns.R;
import com.ncs.cns.activity.CircuseeDetailActivity;
import com.ncs.cns.business.constants.BundleConstants;
import com.ncs.cns.business.constants.MethodConstant;
import com.ncs.cns.business.to.Event;
import com.ncs.cns.business.to.Resource;
import com.ncs.cns.business.to.TransferObject;
import com.ncs.cns.business.util.BundleUtil;
import com.ncs.cns.business.util.DateUtil;
import com.ncs.cns.business.util.JsonConvertor;
import com.ncs.cns.framework.Constant;
import com.ncs.cns.framework.widget.listview.CNSListView;
import com.ncs.cns.framework.widget.listview.CNSListView.IListViewListener;

public class AllCircuSeeFragment extends BaseFragment implements IListViewListener,
		OnItemClickListener {
	private CNSListView mListView;
	private Handler mHandler;
	private MyScrollHandler scrollHandler;
	private MyListAdapter noteBookAdapter;
	private List<Event> eventList;
	private int currentPosition = -1;
	private RefreshTask rtask;
	private LoadMoreTask ltask;
	private Event currentEvent;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_all_circu_see, null);
		initView(view);
		setData();
		setDataAdapter();
		mListView.startRefresh();
		return view;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == Activity.RESULT_OK){
			if(requestCode == 1){
				if(currentEvent != null){
					currentEvent.setEventNumberWatched(data.getIntExtra(BundleConstants.BUNDLE_EVENT_WATCHED,0));
					currentEvent.setEventNumberGood(data.getIntExtra(BundleConstants.BUNDLE_EVENT_GOOD,0));
					currentEvent.setIsPraise(data.getStringExtra(BundleConstants.BUNDLE_EVENT_ISPRAISE));
				}
			}
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> listview, View view, int position,long arg3) {
		currentEvent = eventList.get(position-1);
		Intent intent = new Intent(this.getActivity(), CircuseeDetailActivity.class);	
		Bundle bundle = BundleUtil.buildEventBundle(currentEvent);
		intent.putExtras(bundle);
		startActivityForResult(intent,1);
	}

	private void initView(View view) {
		mListView = (CNSListView) view.findViewById(R.id.circuseeListView);
		mListView.setRefreshTime(sessionService.getLastRefreshTime(currentUserId));
		mListView.setOnItemClickListener(this);
		mListView.setPullLoadEnable(true);
		mListView.setCNSListViewListener(this);
		mHandler = new Handler();
		scrollHandler = new MyScrollHandler();
	}

	private void setData() {
		eventList = eventService.findByExpireDate(0, mListView.PAGE_LIMIT);
		Event e;
		Date now = new Date();
		for(int i = 0;i<eventList.size();i++){
			e = eventList.get(i);
			try {
				if(DateUtil.parse(e.getEventClosingTimeDefault(),DateUtil.yyyy_MM_dd_HH_mm_ss).before(now)){					
					eventService.delete(e.getEventId());
					eventList.remove(i);
					i--;
					continue;
				}
				if(!e.getEventStatus().equals("A")){
					eventList.remove(i);
					i--;
					continue;
				}
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
		}
	}

	private void setDataAdapter() {

		if (noteBookAdapter == null) {
			noteBookAdapter = new MyListAdapter(getActivity(), eventList);
			mListView.setAdapter(noteBookAdapter);

		} else {
			noteBookAdapter.notifyDataSetChanged();
		}

	}

	private void onLoad() {
		mListView.stopRefreshOther();
		mListView.stopLoadMore();
		mListView.setRefreshTime(sessionService.getLastRefreshTime(currentUserId));
	}

	public void onRefresh() {
		new RefreshTask().execute();
	}

	public void onLoadMore() {
		new LoadMoreTask().execute();
	}

	// 定义一个点击事件的内部类，处理整个页面的点击事件

	class MyListAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater inflater;
		private List<Event> dataList;

		public MyListAdapter(Activity activity, List<Event> list) {
			this.context = activity;
			this.dataList = list;
			inflater = LayoutInflater.from(context);
		}

		public void notifyDataSetChanged(List<Event> list) {
			dataList.addAll(list);
		}

		@Override
		public void notifyDataSetChanged() {
			dataList = eventList;
			super.notifyDataSetChanged();
		}

		public int getCount() {

			return dataList.size();
		}

		public int getItemViewType(int position) {
			return position;
		}

		public Object getItem(int arg0) {
			return dataList.get(arg0);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.cns_listview_item,
						parent, false);				
				holder = new ViewHolder();
				holder.layout_item = (LinearLayout) convertView.findViewById(R.id.linearLayout2);
				holder.event_title = (TextView) convertView.findViewById(R.id.text_event_title);
				holder.watched_number = (TextView) convertView.findViewById(R.id.text_watched_number);
				holder.desc = (TextView) convertView.findViewById(R.id.text_event_desc);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			Event event = dataList.get(position);
			if (event!=null) {				
				holder.event_title.setText(event.getEventSubject());
				holder.watched_number.setText(""+event.getEventNumberWatched());
			}
			holder.layout_item.removeView(holder.desc);
			return convertView;
		}

		class ViewHolder {
			public TextView desc;
			public TextView event_desc;
			public LinearLayout layout_item;
			public TextView event_title;
			public TextView event_detail;
			public TextView watched_number;
		}
	}

	@SuppressLint("HandlerLeak")
	class MyScrollHandler extends Handler {// /add by hzm
											// start------------------------
		public MyScrollHandler() {

		}

		// 子类必须重写此方法,接受数据
		@Override
		public void handleMessage(Message msg) {

			super.handleMessage(msg);
			// 此处可以更新UI
			Bundle b = msg.getData();
			final int item = b.getInt("item");

			mListView.startScrollListview(getHeightFromTop(mListView, item));

		}

	}

	public int getHeightFromTop(ListView listView, int currentItem) {

		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null || listAdapter.getCount() == 0) {
			// pre-condition
			return 0;
		}

		int totalHeight = 0;
		Rect r = new Rect();
		int firstVisablePose = listView.getFirstVisiblePosition();

		for (int i = 0; i <= currentItem - firstVisablePose; i++) {
			Boolean flag = listView.getChildAt(i).getGlobalVisibleRect(r); // 必须判断可见与否
			if (flag == true)
				totalHeight += r.height();
		}

		totalHeight = totalHeight
				+ (listView.getDividerHeight() * (currentItem - firstVisablePose));

		return totalHeight;
	}// ----------------------------------------------------------------------------------------end

	class LoadMoreTask extends AsyncTask<Void, Void, List<Event>> {

		@Override
		protected List<Event> doInBackground(Void... params) {
			List<Event> list = eventService.findByExpireDate(mListView.getLastVisiblePosition(), mListView.PAGE_LOAD_SIZE);
			Event e;
			Date now = new Date();
			for(int i = 0;i<eventList.size();i++){
				e = eventList.get(i);
				try {
					if(DateUtil.parse(e.getEventClosingTimeDefault(),DateUtil.yyyy_MM_dd_HH_mm_ss).before(now)){					
						eventService.delete(e.getEventId());
						eventList.remove(i);
						i--;
						continue;
					}
					if(!e.getEventStatus().equals("A")){
						eventList.remove(i);
						i--;
						continue;
					}
				} catch (ParseException e1) {
					e1.printStackTrace();
				}
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<Event> list) {
			ltask = null;
			noteBookAdapter.notifyDataSetChanged(list);
			mListView.stopLoadMore();
		}
	}

	class RefreshTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... arg0) {
			String json = httpHelper.doPost(dbHelper
					.buildParamStr(MethodConstant.RETRIEVE_ALL_CIRCUSEE,currentUserId));
			TransferObject object = (TransferObject) JsonConvertor
					.getInstance().convert2Object(json, TransferObject.class);
			List<Event> events = null;
			if(object!=null )
				events = object.getEventList();
			if (events!=null && events.size() > 0) {
				for (Event e : events) {
					if (eventService.isExist(e.getEventId())){
						e.setIsMy(EVENT_IS_NOT_MY);
						e.setIsRead(Constant.EVENT_N);
						e.setIsPraise(Constant.EVENT_N);
						eventService.add(e);
						for(Resource re:e.getResources()){
							resourceService.add(re);
						}
					}else{
						eventService.updateWatchNumber(e);
						eventService.updateGood(e);
					}
					sessionService.updateLastRefreshTime(currentUserId);
				}
				return true;
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean success) {
			rtask = null;
			setData();
			noteBookAdapter.notifyDataSetChanged();
			//mListView.setAdapter(noteBookAdapter);
			onLoad();
		}

	}

}
